package cn.dylan.pet.service.impl;

import cn.dylan.basic.service.impl.BaseServiceImpl;
import cn.dylan.pet.domain.Pet;
import cn.dylan.pet.domain.PetType;
import cn.dylan.pet.mapper.PetMapper;
import cn.dylan.pet.mapper.PetTypeMapper;
import cn.dylan.pet.service.IPetService;
import cn.dylan.pet.service.IPetTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;


    @Override
    public List<PetType> typeTree() {
        List<PetType> types = petTypeMapper.loadAll();

        Map<Long, PetType> map = new HashMap<>();
        for (PetType type : types) {
            map.put(type.getId(),type);
        }

        List<PetType> typeTree = new ArrayList<>();

        for (PetType type : types) {
            if(type.getPid()==null){
                typeTree.add(type);
            }else {
                Long pid = type.getPid();
                PetType parentType = map.get(pid);
                parentType.getChildren().add(type);
            }
        }

        return typeTree;
    }
}
